<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>卖出的订单</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <!-- 使用与buyer-orders.html相同的样式 -->
    <link rel="stylesheet" href="css/order-common.css">
    <style>
        /* 可以添加卖家订单特有的样式 */
        :root {
            --primary-color: #ffd700;
            --primary-light: #fff7cc;
            --primary-dark: #ffcd00;
            --danger-color: #ff4d4f;
            --success-color: #52c41a;
        }

        body {
            background-color: #fffdf5;
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .order-tabs {
            display: flex;
            margin-bottom: 20px;
            background: white;
            border-radius: 8px;
            padding: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 16px;
            position: relative;
            transition: all 0.3s;
            border-radius: 4px;
        }

        .tab:hover {
            background-color: var(--primary-light);
        }

        .tab.active {
            color: var(--primary-dark);
            background-color: var(--primary-light);
            font-weight: bold;
        }

        .order-item {
            border: 1px solid #eee;
            margin-bottom: 20px;
            border-radius: 8px;
            background-color: white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            transition: all 0.3s;
            cursor: pointer;
        }

        .order-item:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }

        .order-header {
            display: flex;
            justify-content: space-between;
            padding: 15px;
            border-bottom: 1px solid #eee;
            background-color: #fafafa;
            border-radius: 8px 8px 0 0;
        }

        .order-content {
            display: flex;
            padding: 20px;
            gap: 20px;
        }

        .product-image {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: 4px;
        }

        .product-info {
            flex: 1;
        }

        .product-name {
            font-size: 16px;
            margin-bottom: 10px;
            color: #333;
        }

        .product-price {
            color: var(--danger-color);
            font-size: 18px;
            font-weight: bold;
        }

        .order-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border-top: 1px solid #eee;
            background-color: #fafafa;
            border-radius: 0 0 8px 8px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }

        .action-btn {
            padding: 8px 16px;
            border: 1px solid var(--primary-color);
            color: var(--primary-color);
            background: white;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .action-btn.primary {
            background: var(--primary-color);
            color: white;
        }

        .action-btn.danger {
            border-color: var(--danger-color);
            color: var(--danger-color);
        }

        .action-btn:hover {
            opacity: 0.8;
            transform: translateY(-1px);
        }

        .status-tag {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 14px;
            margin-left: 10px;
        }

        .status-pending {
            background-color: #fff7e6;
            color: #fa8c16;
        }

        .status-shipping {
            background-color: #e6f7ff;
            color: #1890ff;
        }

        .status-completed {
            background-color: #f6ffed;
            color: var(--success-color);
        }

        .status-cancelled {
            background-color: #fff1f0;
            color: var(--danger-color);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal-content {
            position: relative;
            width: 500px;
            margin: 100px auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        .modal-close {
            position: absolute;
            top: 15px;
            right: 15px;
            font-size: 20px;
            color: #999;
            cursor: pointer;
            transition: all 0.3s;
        }

        .modal-close:hover {
            color: #666;
        }

        .order-detail-section {
            margin: 15px 0;
            padding: 15px;
            background: #fafafa;
            border-radius: 4px;
        }

        .order-detail-section h3 {
            margin: 0 0 10px 0;
            color: #333;
        }

        .detail-row {
            display: flex;
            margin: 8px 0;
        }

        .detail-label {
            width: 100px;
            color: #666;
        }

        .detail-value {
            flex: 1;
            color: #333;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 20px;
            color: #ddd;
        }

        .star-rating {
            color: #ffd700;
            font-size: 18px;
            margin: 10px 0;
        }

        .comment-time {
            color: #999;
            font-size: 14px;
            margin-top: 10px;
        }

        .comment-content {
            margin: 15px 0;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 4px;
            line-height: 1.6;
        }

        .express-input {
            width: 200px;
            padding: 8px;
            margin-right: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }

        .back-btn {
            background: transparent;
            border: none;
            color: #666;
            cursor: pointer;
            display: flex;
            align-items: center;
            font-size: 14px;
            padding: 8px 12px;
            margin-right: 20px;
            border-radius: 4px;
            transition: all 0.3s;
        }

        .back-btn:hover {
            background: #f5f5f5;
            color: var(--primary-color);
        }

        .back-btn i {
            margin-right: 5px;
        }

        .form-section {
            margin-bottom: 20px;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 4px;
        }

        .form-section h3 {
            margin: 0 0 15px 0;
            color: #333;
            font-size: 16px;
        }

        .info-row {
            margin-bottom: 10px;
            display: flex;
        }

        .info-label {
            width: 80px;
            color: #666;
        }

        .info-value {
            flex: 1;
            color: #333;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #666;
        }

        .form-input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .form-input:focus {
            border-color: var(--primary-color);
            outline: none;
        }

        /* 在已有的style标签中添加评价模态框样式 */
        .star-rating {
            color: #ddd;
            font-size: 24px;
            cursor: pointer;
        }

        .star-rating .star {
            display: inline-block;
            margin-right: 5px;
            transition: color 0.2s;
        }

        .star-rating .star.active {
            color: #ffd700;
        }

        .rating-container {
            margin-bottom: 20px;
        }

        .rating-label {
            margin-bottom: 10px;
            color: #666;
        }

        .comment-input textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
            min-height: 100px;
        }

        .modal-footer {
            margin-top: 20px;
            text-align: right;
        }

        /* 在已有的style标签中添加评论样式 */
        .comment-section {
            margin-top: 15px;
            padding: 10px;
            background: #f9f9f9;
            border-radius: 4px;
        }

        .buyer-comment, .seller-comment {
            padding: 10px;
            border-radius: 4px;
        }

        .seller-comment {
            margin-top: 10px;
            background: #fff;
            border: 1px solid #eee;
        }

        .comment-header {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }

        .comment-title {
            font-weight: bold;
            margin-right: 10px;
            color: #666;
        }

        .comment-content {
            color: #333;
            line-height: 1.5;
            word-break: break-all;
        }

        .star-rating {
            color: #ffd700;
            font-size: 16px;
        }

        /* 评价详情模态框样式 */
        .comment-detail-modal .modal-content {
            max-width: 600px;
        }

        .comment-detail {
            padding: 20px;
        }

        .comment-item {
            margin-bottom: 20px;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 4px;
        }

        .comment-item:last-child {
            margin-bottom: 0;
        }

        .comment-meta {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <button class="back-btn" onclick="goBack()">
                <i class="fas fa-arrow-left"></i>返回
            </button>
        </div>
        <div class="order-tabs">
            <button class="tab active" onclick="filterOrders('all')">全部订单</button>
            <button class="tab" onclick="filterOrders('待付款')">待付款</button>
            <button class="tab" onclick="filterOrders('待发货')">待发货</button>
            <button class="tab" onclick="filterOrders('待收货')">待收货</button>
            <button class="tab" onclick="filterOrders('待评价')">待评价</button>
            <button class="tab" onclick="filterOrders('已评价')">已评价</button>
            <button class="tab" onclick="filterOrders('已取消')">已取消</button>
        </div>

        <div id="orderList">
            <!-- 订单列表将通过JavaScript动态加载 -->
        </div>
    </div>

    <!-- 订单详情模态框 -->
    <div id="orderDetailModal" class="modal">
        <div class="modal-content">
            <span class="modal-close" onclick="closeModal('orderDetailModal')">&times;</span>
            <h2>订单详情</h2>
            <div id="orderDetailContent"></div>
        </div>
    </div>

    <!-- 发货模态框 -->
    <div id="shipModal" class="modal">
        <div class="modal-content">
            <span class="modal-close" onclick="closeModal('shipModal')">&times;</span>
            <h2>填写发货信息</h2>
            <div class="ship-form">
                <!-- 发货信息展示区域 -->
                <div class="form-section">
                    <h3>收货信息</h3>
                    <div class="info-row">
                        <span class="info-label">收货人：</span>
                        <span id="recipientName" class="info-value"></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">联系电话：</span>
                        <span id="recipientPhone" class="info-value"></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">收货地址：</span>
                        <span id="recipientAddress" class="info-value"></span>
                    </div>
                </div>
                <!-- 发货信息输入区域 -->
                <div class="form-section">
                    <h3>发货信息</h3>
                    <div class="form-group">
                        <label>快递公司：</label>
                        <input type="text" id="companyName" class="form-input" placeholder="请输入快递公司名称">
                    </div>
                    <div class="form-group">
                        <label>快递单号：</label>
                        <input type="text" id="expressNo" class="form-input" placeholder="请输入快递单号">
                    </div>
                    <div class="form-group">
                        <label>发货人姓名：</label>
                        <input type="text" id="senderName" class="form-input" placeholder="请输入发货人姓名">
                    </div>
                    <div class="form-group">
                        <label>发货人电话：</label>
                        <input type="text" id="senderPhone" class="form-input" placeholder="请输入发货人手机号">
                    </div>
                    <div class="form-group">
                        <label>发货地址：</label>
                        <input type="text" id="senderAddress" class="form-input" placeholder="请输入发货地址">
                    </div>
                </div>
                <div class="action-buttons" style="margin-top: 15px;">
                    <button class="action-btn primary" onclick="confirmShip()">确认发货</button>
                    <button class="action-btn" onclick="closeModal('shipModal')">取消</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 取消订单模态框 -->
    <div id="cancelOrderModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>取消订单</h2>
                <span class="close" onclick="closeModal('cancelOrderModal')">&times;</span>
            </div>
            <div class="modal-body">
                <div class="form-section">
                    <div class="form-group">
                        <label>取消原因：</label>
                        <textarea id="cancelReason" class="form-input" style="height: 100px; resize: vertical;" 
                            placeholder="请输入取消原因（必填）"></textarea>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="action-btn" onclick="closeModal('cancelOrderModal')">关闭</button>
                <button class="action-btn danger" onclick="confirmCancelOrder()">确认取消</button>
            </div>
        </div>
    </div>

    <!-- 查看取消原因模态框 -->
    <div id="viewCancelReasonModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>取消原因</h2>
                <span class="close" onclick="closeModal('viewCancelReasonModal')">&times;</span>
            </div>
            <div class="modal-body">
                <div class="form-section">
                    <div class="info-row">
                        <span class="info-label">订单号：</span>
                        <span id="cancelOrderNo" class="info-value"></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">取消时间：</span>
                        <span id="cancelTime" class="info-value"></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">取消原因：</span>
                        <div id="viewCancelReason" class="info-value" style="white-space: pre-wrap;"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="action-btn" onclick="closeModal('viewCancelReasonModal')">关闭</button>
            </div>
        </div>
    </div>

    <!-- 物流信息模态框 -->
    <div id="expressModal" class="modal">
        <div class="modal-content">
            <span class="modal-close" onclick="closeModal('expressModal')">&times;</span>
            <h2>物流信息</h2>
            <div class="express-info">
                <div class="form-section">
                    <h3>快递信息</h3>
                    <div class="info-row">
                        <span class="info-label">快递单号：</span>
                        <span id="expressNoDisplay" class="info-value"></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">快递公司：</span>
                        <span id="companyNameDisplay" class="info-value"></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">发货时间：</span>
                        <span id="sendTimeDisplay" class="info-value"></span>
                    </div>
                </div>
                <div class="form-section">
                    <h3>发货信息</h3>
                    <div class="info-row">
                        <span class="info-label">发货人：</span>
                        <span id="senderNameDisplay" class="info-value"></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">联系电话：</span>
                        <span id="senderPhoneDisplay" class="info-value"></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">发货地址：</span>
                        <span id="senderAddressDisplay" class="info-value"></span>
                    </div>
                </div>
                <div class="form-section">
                    <h3>收货信息</h3>
                    <div class="info-row">
                        <span class="info-label">收货人：</span>
                        <span id="receiverNameDisplay" class="info-value"></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">联系电话：</span>
                        <span id="receiverPhoneDisplay" class="info-value"></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">收货地址：</span>
                        <span id="receiverAddressDisplay" class="info-value"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 评价模态框 -->
    <div id="commentModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>评价订单</h2>
                <span class="close" onclick="closeModal('commentModal')">&times;</span>
            </div>
            <div class="modal-body">
                <div class="rating-container">
                    <div class="rating-label">评分：</div>
                    <div class="star-rating">
                        <span class="star" data-rating="1" onclick="setRating(1)">★</span>
                        <span class="star" data-rating="2" onclick="setRating(2)">★</span>
                        <span class="star" data-rating="3" onclick="setRating(3)">★</span>
                        <span class="star" data-rating="4" onclick="setRating(4)">★</span>
                        <span class="star" data-rating="5" onclick="setRating(5)">★</span>
                    </div>
                </div>
                <div class="comment-input">
                    <textarea id="commentContent" placeholder="请输入您的评价内容..." rows="4"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="action-btn" onclick="closeModal('commentModal')">取消</button>
                <button class="action-btn primary" onclick="submitComment()">提交评价</button>
            </div>
        </div>
    </div>

    <!-- 修改评价详情模态框 -->
    <div id="commentDetailModal" class="modal comment-detail-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>评价详情</h2>
                <span class="close" onclick="closeModal('commentDetailModal')">&times;</span>
            </div>
            <div class="comment-detail" id="commentDetailContent">
                <!-- 评价详情将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>

    <!-- 卖家评价模态框 -->
    <div id="sellerCommentModal" class="modal" style="display: none;">
        <div class="modal-content">
            <span class="modal-close" onclick="closeSellerCommentModal()">&times;</span>
            <h2>评价订单</h2>
            <div class="rating-container">
                <div class="rating-label">评分：</div>
                <div class="star-rating">
                    <span class="seller-star" data-rating="1" onclick="setSellerRating(1)">★</span>
                    <span class="seller-star" data-rating="2" onclick="setSellerRating(2)">★</span>
                    <span class="seller-star" data-rating="3" onclick="setSellerRating(3)">★</span>
                    <span class="seller-star" data-rating="4" onclick="setSellerRating(4)">★</span>
                    <span class="seller-star" data-rating="5" onclick="setSellerRating(5)">★</span>
                </div>
            </div>
            <div class="comment-input">
                <textarea id="sellerCommentContent" placeholder="请输入您的评价内容..." rows="4"></textarea>
            </div>
            <div class="modal-footer">
                <button class="action-btn" onclick="closeSellerCommentModal()">取消</button>
                <button class="action-btn primary" onclick="submitSellerComment()">提交评价</button>
            </div>
        </div>
    </div>

    <script>
        let currentOrderNo = null;
        let currentRating = 0;
        
        // 加载订单列表
        function loadOrders(status = 'all') {
            let url = '/seller/order/list';
            let apiStatus = status;
            
            // 如果是待评价或已评价状态，使用新的接口
            if (status === '待评价' || status === '已评价') {
                url = '/seller/order/listComment';
                apiStatus = status;
            }
            
            $.ajax({
                url: url,
                type: 'GET',
                data: { status: apiStatus },
                success: function(response) {
                    console.log('========== 加载订单列表 ==========');
                    console.log('请求状态:', status);
                    console.log('接口地址:', url);
                    console.log('返回数据:', response);
                    console.log('================================');
                    
                    if (response.state === 1) {
                        renderOrders(response.data);
                    } else {
                        showEmptyState('加载订单失败');
                    }
                },
                error: function(error) {
                    console.error('========== 加载订单失败 ==========');
                    console.error('错误信息:', error);
                    console.error('================================');
                    showEmptyState('加载订单失败');
                }
            });
        }

        // 渲染订单列表
        function renderOrders(orders) {
            const orderList = $('#orderList');
            orderList.empty();

            if (!orders || orders.length === 0) {
                showEmptyState('暂无订单');
                return;
            }

            orders.forEach(order => {
                // 确定显示的状态
                let displayStatus = order.status;
                
                // 如果是从评价接口获取的数据，使用评价状态
                if (order.sellerCommentStatus) {
                    displayStatus = order.sellerCommentStatus;
                }
                
                const statusText = getStatusText(displayStatus);
                const statusClass = getStatusClass(displayStatus);
                
                console.log('========== 订单信息 ==========');
                console.log('订单号:', order.orderNo);
                console.log('状态:', displayStatus);
                console.log('买家:', order.buyerNickname);
                console.log('商品:', order.name);
                console.log('价格:', order.price);
                console.log('============================');
                
                const orderHtml = `
                    <div class="order-item" onclick="viewOrderDetail('${order.orderNo}')">
                        <div class="order-header">
                            <div>
                                <span>订单号：${order.orderNo}</span>
                                <span class="status-tag ${statusClass}">${statusText}</span>
                            </div>
                            <div>
                                <span>买家：${order.buyerNickname || '未知买家'}</span>
                                <button class="action-btn" onclick="event.stopPropagation(); startChat(${order.buyerId}, ${order.productId})">
                                    联系买家
                                </button>
                                <span style="margin-left: 20px;">下单时间：${new Date(order.createTime).toLocaleString()}</span>
                            </div>
                        </div>
                        <div class="order-content">
                            <img src="${order.firstImage}" class="product-image" 
                                 alt="${order.name}"
                                 onerror="this.src='images/default-product.png'">
                            <div class="product-info">
                                <div class="product-name">${order.name}</div>
                                <div class="product-price">¥${order.price.toFixed(2)}</div>
                            </div>
                        </div>
                        <div class="order-footer">
                            <div class="order-total">
                                <span>实付款：<span class="product-price">¥${order.price.toFixed(2)}</span></span>
                                ${order.expressNo ? `
                                    <span style="margin-left: 20px; color: #666;">
                                        快递单号：${order.expressNo}
                                    </span>
                                ` : ''}
                            </div>
                            <div class="action-buttons" onclick="event.stopPropagation();">
                                ${getActionButtons(order)}
                            </div>
                        </div>
                    </div>
                `;
                orderList.append(orderHtml);
            });
        }

        // 获取操作按钮
        function getActionButtons(order) {
            let buttons = [];
            
            switch(order.status) {
                case '待付款':
                    buttons.push(`<button class="action-btn warning" onclick="cancelOrder('${order.orderNo}')">取消订单</button>`);
                    break;
                case '待发货':
                    buttons.push(`<button class="action-btn primary" onclick="showShipModal('${order.orderNo}')">发货</button>`);
                    buttons.push(`<button class="action-btn warning" onclick="cancelOrder('${order.orderNo}')">取消订单</button>`);
                    break;
                case '待收货':
                    buttons.push(`<button class="action-btn" onclick="viewExpress('${order.orderNo}')">查看物流</button>`);
                    break;
                case '待评价':
                    buttons.push(`<button class="action-btn primary" onclick="showSellerCommentModal('${order.orderNo}')">评价买家</button>`);
                    buttons.push(`<button class="action-btn" onclick="viewExpress('${order.orderNo}')">查看物流</button>`);
                    break;
                case '已评价':
                    buttons.push(`<button class="action-btn" onclick="viewComment('${order.orderNo}')">查看评价</button>`);
                    buttons.push(`<button class="action-btn" onclick="viewExpress('${order.orderNo}')">查看物流</button>`);
                    buttons.push(`<button class="action-btn danger" onclick="deleteOrder('${order.orderNo}')">删除订单</button>`);
                    break;
                case '已取消':
                    buttons.push(`<button class="action-btn" onclick="viewCancelReason('${order.orderNo}')">查看取消原因</button>`);
                    buttons.push(`<button class="action-btn danger" onclick="deleteOrder('${order.orderNo}')">删除订单</button>`);
                    break;
            }
            
            return buttons.join('');
        }

        // 查看评价详情
        function viewAllComments(orderNo) {
            event.stopPropagation();
            $.ajax({
                url: `/comment/get/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        const comment = response.data;
                        const commentHtml = `
                            <div class="comment-item">
                                <div class="comment-header">
                                    <span class="comment-title">买家评价</span>
                                    <div class="star-rating">
                                        ${'★'.repeat(comment.rating)}${'☆'.repeat(5-comment.rating)}
                                    </div>
                                </div>
                                <div class="comment-content">${comment.content || '暂无评价内容'}</div>
                                <div class="comment-meta">
                                    <span>评价时间：${new Date(comment.createTime).toLocaleString()}</span>
                                </div>
                            </div>
                            ${comment.sellerContent ? `
                                <div class="comment-item">
                                    <div class="comment-header">
                                        <span class="comment-title">卖家回复</span>
                                        <div class="star-rating">
                                            ${'★'.repeat(comment.sellerRating)}${'☆'.repeat(5-comment.sellerRating)}
                                        </div>
                                    </div>
                                    <div class="comment-content">${comment.sellerContent}</div>
                                    <div class="comment-meta">
                                        <span>回复时间：${new Date(comment.updateTime).toLocaleString()}</span>
                                    </div>
                                </div>
                            ` : ''}
                        `;
                        $('#commentDetailContent').html(commentHtml);
                        showModal('commentDetailModal');
                    } else {
                        alert('获取评价详情失败');
                    }
                }
            });
        }

        // 设置评分
        function setRating(rating) {
            currentRating = rating;
            const stars = document.querySelectorAll('.star-rating .star');
            stars.forEach((star, index) => {
                star.classList.toggle('active', index < rating);
            });
        }

        // 显示评价模态框
        function showCommentModal(orderNo) {
            event.stopPropagation();
            $.ajax({
                url: `/comment/get/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        const comment = response.data;
                        // 如果卖家已经评价，显示提示并返回
                        if (comment.sellerCommentStatus === '已评价') {
                            alert('该订单已评价，无法再次评价');
                            return;
                        }
                        
                        // 重置评价表单
                        currentOrderNo = orderNo;
                        currentRating = 0;
                        document.getElementById('commentContent').value = '';
                        const stars = document.querySelectorAll('.star-rating .star');
                        stars.forEach(star => star.classList.remove('active'));
                        
                        showModal('commentModal');
                    } else {
                        alert('获取评价信息失败');
                    }
                }
            });
        }

        // 提交评价
        function submitComment() {
            const content = document.getElementById('commentContent').value.trim();
            
            if (!content) {
                alert('请输入评价内容');
                return;
            }
            
            if (currentRating === 0) {
                alert('请选择评分');
                return;
            }

            const commentData = {
                orderNo: currentOrderNo,
                content: content,
                rating: currentRating
            };

            $.ajax({
                url: '/comment/seller/submit',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(commentData),
                success: function(response) {
                    if (response.state === 1) {
                        alert('评价成功');
                        closeModal('commentModal');
                        loadOrders('待评价'); // 刷新订单列表
                    } else {
                        alert(response.msg || '评价失败');
                    }
                },
                error: function() {
                    alert('评价失败，请稍后重试');
                }
            });
        }

        // 显示发货模态框
        function showShipModal(orderNo) {
            event.stopPropagation();
            currentOrderNo = orderNo;
            
            // 获取订单详情，显示收货信息
            $.ajax({
                url: `/seller/order/detail/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    console.log('========== 订单详情 ==========');
                    console.log('订单号:', orderNo);
                    console.log('返回数据:', response);
                    console.log('============================');
                    
                    if (response.state === 1) {
                        const order = response.data;
                        // 填充收货信息
                        $('#recipientName').text(order.buyerNickname);
                        $('#recipientPhone').text(order.buyerPhone);
                        $('#recipientAddress').text(order.buyerAddress);
                        
                        // 清空发货表单
                        $('#companyName').val('');
                        $('#expressNo').val('');
                        $('#senderName').val('');
                        $('#senderPhone').val('');
                        $('#senderAddress').val('');
                        
                        showModal('shipModal');
                    } else {
                        alert('获取订单信息失败');
                    }
                }
            });
        }

        // 确认发货
        function confirmShip() {
            const companyName = $('#companyName').val().trim();
            const expressNo = $('#expressNo').val().trim();
            const senderName = $('#senderName').val().trim();
            const senderPhone = $('#senderPhone').val().trim();
            const senderAddress = $('#senderAddress').val().trim();
            const receiverAddress = $('#recipientAddress').text().trim();

            // 验证表单
            if (!companyName) {
                alert('请输入快递公司名称');
                return;
            }
            if (!expressNo) {
                alert('请输入快递单号');
                return;
            }
            if (!senderName) {
                alert('请输入发货人姓名');
                return;
            }
            if (!senderPhone) {
                alert('请输入发货人电话');
                return;
            }
            if (!senderAddress) {
                alert('请输入发货地址');
                return;
            }

            // 验证手机号格式
            if (!/^1[3-9]\d{9}$/.test(senderPhone)) {
                alert('请输入正确的手机号');
                return;
            }

            $.ajax({
                url: '/seller/order/ship',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    orderNo: currentOrderNo,
                    expressNo: expressNo,
                    companyName: companyName,
                    senderName: senderName,
                    senderPhone: senderPhone,
                    senderAddress: senderAddress,
                    receiverAddress: receiverAddress
                }),
                success: function(response) {
                    if (response.state === 1) {
                        alert('发货成功');
                        closeModal('shipModal');
                        loadOrders(); // 刷新订单列表
                    } else {
                        alert(response.msg || '发货失败');
                    }
                }
            });
        }

        // 联系买家
        function startChat(buyerId, productId) {
            if (!buyerId) {
                alert('无法获取买家信息');
                return;
            }
            window.open(`/chat.html?buyerId=${buyerId}&productId=${productId}`, '_blank');
        }

        // 查看评价
        function viewComment(orderNo) {
            event.stopPropagation();
            $.ajax({
                url: `/comment/get/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        const comment = response.data;
                        const stars = '★'.repeat(comment.rating) + '☆'.repeat(5 - comment.rating);
                        const commentHtml = `
                            <div class="star-rating">${stars}</div>
                            <div class="comment-content">${comment.content}</div>
                            <div class="comment-time">评价时间：${new Date(comment.createTime).toLocaleString()}</div>
                        `;
                        $('#commentContent').html(commentHtml);
                        showModal('commentModal');
                    } else {
                        alert('获取评价详情失败');
                    }
                }
            });
        }

        // 查看物流
        function viewExpress(orderNo) {
            event.stopPropagation();
            $.ajax({
                url: `/seller/order/express/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    console.log('========== 物流信息 ==========');
                    console.log('订单号:', orderNo);
                    console.log('返回数据:', response);
                    console.log('============================');
                    
                    if (response.state === 1) {
                        const express = response.data;
                        
                        // 填物流信息
                        $('#expressNoDisplay').text(express.expressNo || '暂无');
                        $('#companyNameDisplay').text(express.companyName || '暂无');
                        $('#sendTimeDisplay').text(express.sendTime ? new Date(express.sendTime).toLocaleString() : '暂无');
                        
                        // 填充发货信息
                        $('#senderNameDisplay').text(express.senderName || '暂无');
                        $('#senderPhoneDisplay').text(express.senderPhone || '暂无');
                        $('#senderAddressDisplay').text(express.senderAddress || '暂无');
                        
                        // 填充收货信息
                        $('#receiverNameDisplay').text(express.receiverName || '暂无');
                        $('#receiverPhoneDisplay').text(express.receiverPhone || '暂无');
                        $('#receiverAddressDisplay').text(express.receiverAddress || '暂无');
                        
                        showModal('expressModal');
                    } else {
                        alert('获取物流信息失败');
                    }
                }
            });
        }

        // 查看取消原因
        function viewCancelReason(orderNo) {
            event.stopPropagation();
            $.ajax({
                url: `/seller/order/cancel-reason/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    console.log('========== 查看取消原因 ==========');
                    console.log('订单号:', orderNo);
                    console.log('返回数据:', response);
                    console.log('============================');
                    
                    if (response.state === 1) {
                        $('#cancelOrderNo').text(orderNo);
                        $('#cancelTime').text(new Date(response.data.cancelTime).toLocaleString());
                        $('#viewCancelReason').text(response.data.reason || '未填写取消原因');
                        showModal('viewCancelReasonModal');
                    } else {
                        // 使用模态框显示错误信息
                        showErrorMessage('获取取消原因失败');
                    }
                },
                error: function(error) {
                    console.error('========== 获取取消原因失败 ==========');
                    console.error('订单号:', orderNo);
                    console.error('错误信息:', error);
                    console.error('================================');
                    showErrorMessage('获取取消原因失败，请稍后重试');
                }
            });
        }

        // 显示订单详情
        function viewOrderDetail(orderNo) {
            $.ajax({
                url: `/seller/order/detail/${orderNo}`,
                type: 'GET',
                success: function(response) {
                    console.log('========== 订单详情 ==========');
                    console.log('订单号:', orderNo);
                    console.log('返回数据:', response);
                    console.log('============================');
                    
                    if (response.state === 1) {
                        const order = response.data;
                        const detailHtml = `
                            <div class="order-detail-section">
                                <h3>基本信息</h3>
                                <div class="detail-row">
                                    <span class="detail-label">订单状态：</span>
                                    <span class="detail-value">${getStatusText(order.status)}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">买家：</span>
                                    <span class="detail-value">
                                        ${order.buyerNickname || '未知买家'}
                                        <button class="action-btn" onclick="startChat(${order.buyerId}, ${order.productId})">
                                            联系买家
                                        </button>
                                    </span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">创建时间：</span>
                                    <span class="detail-value">${new Date(order.createTime).toLocaleString()}</span>
                                </div>
                                ${order.paymentTime ? `
                                    <div class="detail-row">
                                        <span class="detail-label">支付时间：</span>
                                        <span class="detail-value">${new Date(order.paymentTime).toLocaleString()}</span>
                                    </div>
                                ` : ''}
                                ${order.deliveryTime ? `
                                    <div class="detail-row">
                                        <span class="detail-label">发货时间：</span>
                                        <span class="detail-value">${new Date(order.deliveryTime).toLocaleString()}</span>
                                    </div>
                                ` : ''}
                                ${order.completionTime ? `
                                    <div class="detail-row">
                                        <span class="detail-label">完成时间：</span>
                                        <span class="detail-value">${new Date(order.completionTime).toLocaleString()}</span>
                                    </div>
                                ` : ''}
                            </div>
                            
                            <div class="order-detail-section">
                                <h3>商品信息</h3>
                                <div class="detail-row">
                                    <span class="detail-label">商品名称：</span>
                                    <span class="detail-value">${order.productName}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">商品价格：</span>
                                    <span class="detail-value product-price">¥${order.price.toFixed(2)}</span>
                                </div>
                            </div>
                            
                            <div class="order-detail-section">
                                <h3>收货信息</h3>
                                <div class="detail-row">
                                    <span class="detail-label">收货人：</span>
                                    <span class="detail-value">${order.recipientName}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">联系电话：</span>
                                    <span class="detail-value">${order.recipientPhone}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">收货地址：</span>
                                    <span class="detail-value">${order.recipientAddress}</span>
                                </div>
                            </div>
                            
                            ${order.expressNo ? `
                                <div class="order-detail-section">
                                    <h3>物流信息</h3>
                                    <div class="detail-row">
                                        <span class="detail-label">快递单号：</span>
                                        <span class="detail-value">${order.expressNo}</span>
                                    </div>
                                    <div class="detail-row">
                                        <span class="detail-label">发货时间：</span>
                                        <span class="detail-value">${new Date(order.deliveryTime).toLocaleString()}</span>
                                    </div>
                                </div>
                            ` : ''}
                            
                            ${order.remark ? `
                                <div class="order-detail-section">
                                    <h3>备注信息</h3>
                                    <div class="detail-row">
                                        <span class="detail-value">${order.remark}</span>
                                    </div>
                                </div>
                            ` : ''}
                        `;
                        
                        $('#orderDetailContent').html(detailHtml);
                        showModal('orderDetailModal');
                    } else {
                        alert('获取订单详情失败');
                    }
                }
            });
        }

        // 显示空状态
        function showEmptyState(message) {
            $('#orderList').html(`
                <div class="empty-state">
                    <i class="fas fa-box-open"></i>
                    <p>${message}</p>
                </div>
            `);
        }

        // 显示模态框
        function showModal(modalId) {
            $(`#${modalId}`).fadeIn(200);
        }

        // 关闭模态框
        function closeModal(modalId) {
            $(`#${modalId}`).fadeOut(200);
        }

        // 切换订单状态
        function filterOrders(status) {
            $('.tab').removeClass('active');
            $(event.target).addClass('active');
            loadOrders(status);
        }

        // 获取状态对应的类名
        function getStatusClass(status) {
            const statusMap = {
                '待付款': 'status-pending',
                '待发货': 'status-shipping',
                '待收货': 'status-shipping',
                '待评价': 'status-completed',
                '已评价': 'status-completed',
                '已取消': 'status-cancelled'
            };
            return statusMap[status] || '';
        }

        // 获取状态文本
        function getStatusText(status) {
            return status || '未知状态';
        }

        // 显示取消订单模态框
        function showCancelOrderModal(orderNo) {
            event.stopPropagation();
            currentOrderNo = orderNo;
            $('#cancelReason').val('').focus();
            showModal('cancelOrderModal');
        }

        // 确认取消订单
        function confirmCancelOrder() {
            const reason = $('#cancelReason').val().trim();
            if (!reason) {
                showErrorMessage('请输入取消原因');
                return;
            }

            $.ajax({
                url: '/seller/order/cancel',
                type: 'POST',
                data: {
                    orderNo: currentOrderNo,
                    reason: reason
                },
                success: function(response) {
                    console.log('========== 取消订单 ==========');
                    console.log('订单号:', currentOrderNo);
                    console.log('返回数据:', response);
                    console.log('============================');
                    
                    if (response.state === 1) {
                        showSuccessMessage('订单已取消');
                        closeModal('cancelOrderModal');
                        loadOrders();
                    } else {
                        showErrorMessage(response.msg || '取消订单失败');
                    }
                },
                error: function(error) {
                    console.error('========== 取消订单失败 ==========');
                    console.error('订单号:', currentOrderNo);
                    console.error('错误信息:', error);
                    console.error('================================');
                    showErrorMessage('取消订单失败，请稍后重试');
                }
            });
        }

        // 删除订单
        function deleteOrder(orderNo) {
            if (!confirm('确定要删除该订单吗？此操作不可恢复。')) {
                return;
            }

            $.ajax({
                url: '/seller/order/delete',
                type: 'POST',
                data: { orderNo: orderNo },
                success: function(response) {
                    console.log('========== 删除订单 ==========');
                    console.log('订单号:', orderNo);
                    console.log('返回数据:', response);
                    console.log('============================');
                    
                    if (response.state === 1) {
                        alert('订单已删除');
                        loadOrders();
                    } else {
                        alert(response.msg || '删除订单失败');
                    }
                },
                error: function(error) {
                    console.error('========== 删除订单失败 ==========');
                    console.error('订单号:', orderNo);
                    console.error('错误信息:', error);
                    console.error('================================');
                    alert('删除订单失败，请稍后重试');
                }
            });
        }

        // 返回上一页
        function goBack() {
            if (document.referrer) {
                window.location.href = document.referrer;
            } else {
                window.history.back();
            }
        }

        // 显示错误信息的模态框
        function showErrorMessage(message) {
            const errorHtml = `
                <div class="modal-content" style="max-width: 400px;">
                    <div class="modal-header">
                        <h2>提示</h2>
                        <span class="close" onclick="closeModal('messageModal')">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="form-section" style="text-align: center; color: var(--danger-color);">
                            <i class="fas fa-exclamation-circle" style="font-size: 24px; margin-bottom: 10px;"></i>
                            <p>${message}</p>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="action-btn" onclick="closeModal('messageModal')">确定</button>
                    </div>
                </div>
            `;
            
            showCustomModal('messageModal', errorHtml);
        }

        // 显示成功信息的模态框
        function showSuccessMessage(message) {
            const successHtml = `
                <div class="modal-content" style="max-width: 400px;">
                    <div class="modal-header">
                        <h2>提示</h2>
                        <span class="close" onclick="closeModal('messageModal')">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="form-section" style="text-align: center; color: var(--success-color);">
                            <i class="fas fa-check-circle" style="font-size: 24px; margin-bottom: 10px;"></i>
                            <p>${message}</p>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="action-btn" onclick="closeModal('messageModal')">确定</button>
                    </div>
                </div>
            `;
            
            showCustomModal('messageModal', successHtml);
        }

        // 显示自定义模态框
        function showCustomModal(modalId, content) {
            // 如果模态框不存在，创建它
            if (!$(`#${modalId}`).length) {
                $('body').append(`<div id="${modalId}" class="modal"></div>`);
            }
            
            $(`#${modalId}`).html(content).fadeIn(200);
        }

        // 提交卖家评价
        function submitSellerComment() {
            const content = document.getElementById('sellerCommentContent').value.trim();
            const rating = document.querySelectorAll('.seller-star.active').length;
            
            if (!content) {
                alert('请输入评价内容');
                return;
            }
            
            if (rating === 0) {
                alert('请选择评分');
                return;
            }

            const commentData = {
                orderNo: currentOrderNo,
                content: content,
                rating: rating
            };

            // 提交卖家评价
            $.ajax({
                url: '/comment/seller/submit',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(commentData),
                success: function(response) {
                    if (response.state === 1) {
                        // 更新买家信誉分
                        $.ajax({
                            url: '/user/update-credit',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify({
                                orderNo: currentOrderNo,
                                rating: rating,
                                type: 'buyer' // 表示更新买家信誉分
                            }),
                            success: function(creditResponse) {
                                if (creditResponse.state === 1) {
                                    console.log('买家信誉分更新成功');
                                } else {
                                    console.error('买家信誉分更新失败:', creditResponse.msg);
                                }
                            },
                            error: function(error) {
                                console.error('买家信誉分更新失败:', error);
                            }
                        });
                        
                        alert('评价成功');
                        closeSellerCommentModal();
                        loadOrders(); // 刷新订单列表
                    } else {
                        alert(response.msg || '评价失败，请重试');
                    }
                },
                error: function(error) {
                    console.error('提交评价失败:', error);
                    alert('评价失败，请稍后重试');
                }
            });
        }

        // 显示卖家评价模态框
        function showSellerCommentModal(orderNo) {
            event.stopPropagation();
            currentOrderNo = orderNo;
            document.getElementById('sellerCommentModal').style.display = 'block';
            
            // 重置评价表单
            const textarea = document.getElementById('sellerCommentContent');
            textarea.value = '';
            textarea.readOnly = false;
            textarea.style.backgroundColor = '#fff';
            
            // 重置星级
            const stars = document.querySelectorAll('.seller-star');
            stars.forEach(star => {
                star.classList.remove('active');
                star.style.cursor = 'pointer';
                star.style.pointerEvents = 'auto';
            });
        }

        // 关闭卖家评价模态框
        function closeSellerCommentModal() {
            document.getElementById('sellerCommentModal').style.display = 'none';
        }

        // 星级评分处理
        document.querySelectorAll('.seller-star').forEach(star => {
            star.addEventListener('click', function() {
                const rating = this.dataset.rating;
                document.querySelectorAll('.seller-star').forEach(s => {
                    s.classList.toggle('active', s.dataset.rating <= rating);
                });
            });
        });

        // 页面加载完成后执行
        $(document).ready(function() {
            loadOrders();
        });
    </script>
</body>
</html>